package com.suse.service.community.controller;

import cn.hutool.core.util.ObjectUtil;
import com.suse.common.base.model.entity.Page;
import com.suse.common.config.response.R;
import com.suse.service.community.constant.EntityTypeConstant;
import com.suse.service.community.constant.PostConstant;
import com.suse.service.community.constant.TopicConstant;
import com.suse.service.community.entity.Comment;
import com.suse.service.community.entity.DiscussPost;
import com.suse.service.community.entity.User;
import com.suse.service.community.kafka.Event;
import com.suse.service.community.kafka.EventProducer;
import com.suse.service.community.service.CommentService;
import com.suse.service.community.service.DiscussPostService;
import com.suse.service.community.service.LikeService;
import com.suse.service.community.service.UserService;
import com.suse.service.community.util.RedisUtil;
import com.suse.service.community.util.UserHolder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 讨论发布前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-31 15:32
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController {

    @Resource
    private DiscussPostService discussPostService;

    @Resource
    private UserService userService;

    @Resource
    private CommentService commentService;

    @Resource
    private LikeService likeService;

    @Resource
    private EventProducer eventProducer;

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;

    // @PostMapping("/save")
    // @ResponseBody
    // 巨大的BUG
    @RequestMapping(path = "/save",method = RequestMethod.GET)
    @ResponseBody
    public R save(DiscussPost discussPost) {
        User user = UserHolder.getUser();
        discussPost.setUserId(user.getId());
        discussPost.setCreateTime(new Date());
        discussPostService.save(discussPost);
        Integer postId = discussPost.getId();
        // 发布发帖消息
        Event event = new Event();
        event.setTopic(TopicConstant.PUBLISH);
        event.put("postId",postId);
        eventProducer.fireEvent(event);
        // 将帖子ID放入Redis的待刷新集合中 无序不重复集合
        redisTemplate.opsForSet().add(RedisUtil.getNeedRefreshScorePostsKey(),postId);
        return R.success("发布成功!");
    }

    @GetMapping("/detail/{id}")
    public String getDetail(@PathVariable("id") int id, Model model, Page page) {
        DiscussPost post = discussPostService.getById(id);
        // 帖子信息
        model.addAttribute("post",post);
        User user = userService.getUserById(post.getUserId());
        // 用户信息
        model.addAttribute("user",user);
        // 帖子点赞信息
        long likeCount = likeService.getEntityLikeCount(EntityTypeConstant.POST, post.getId());
        int likeStatus = likeService.getEntityLikeStatus(EntityTypeConstant.POST, post.getId());
        model.addAttribute("likeCount",likeCount);
        model.addAttribute("likeStatus",likeStatus);
        // 评论分页
        page.setLimit(5);
        page.setPath("/discuss/detail/" + id);
        page.setTotal(post.getCommentCount());
        model.addAttribute("page",page);
        // 评论：给帖子的评论
        // 恢复：给评论的评论
        // 评论列表
        List<Comment> commentList = commentService.getListByEntity(EntityTypeConstant.POST, post.getId(), page.getOffset(), page.getLimit());
        // 评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        for (Comment comment : commentList) {
            // 评论VO
            Map<String,Object> commentVo = new HashMap<>();
            // 点赞状态
            likeStatus = likeService.getEntityLikeStatus(EntityTypeConstant.COMMENT, comment.getId());
            commentVo.put("likeStatus",likeStatus);
            // 点赞数
            likeCount = likeService.getEntityLikeCount(EntityTypeConstant.COMMENT, comment.getId());
            commentVo.put("likeCount",likeCount);
            // 评论
            commentVo.put("comment",comment);
            // 评论的人
            commentVo.put("user",userService.getUserById(comment.getUserId()));
            // 回复数
            commentVo.put("replyCount",commentService.getTotalByEntity(EntityTypeConstant.COMMENT, comment.getId()));
            // 回复列表
            List<Comment> replyList = commentService.getListByEntity(EntityTypeConstant.COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
            // 回复VO列表
            List<Map<String, Object>> replyVoList = new ArrayList<>();
            for (Comment reply : replyList) {
                // 回复VO
                Map<String, Object> replyVo = new HashMap<>();
                // 点赞状态
                likeStatus = likeService.getEntityLikeStatus(EntityTypeConstant.COMMENT, reply.getId());
                replyVo.put("likeStatus",likeStatus);
                // 点赞数
                likeCount = likeService.getEntityLikeCount(EntityTypeConstant.COMMENT, reply.getId());
                replyVo.put("likeCount",likeCount);
                // 回复
                replyVo.put("reply",reply);
                // 回复的人
                replyVo.put("user",userService.getUserById(reply.getUserId()));
                // 回复的目标
                if (ObjectUtil.isNotNull(reply.getTargetId())) {
                    replyVo.put("target",userService.getUserById(reply.getTargetId()));
                }
                replyVoList.add(replyVo);
            }
            commentVo.put("replyList",replyVoList);
            commentVoList.add(commentVo);
        }
        model.addAttribute("commentList",commentVoList);
        return "site/discuss-detail";
    }

    @GetMapping("/setTop")
    @ResponseBody
    public R setTop(int id) {
        discussPostService.updateType(id, PostConstant.TOP);
        // 发布发帖消息
        Event event = new Event();
        event.setTopic(TopicConstant.PUBLISH);
        event.put("postId",id);
        eventProducer.fireEvent(event);
        return R.success();
    }

    @GetMapping("/setEssence")
    @ResponseBody
    public R setEssence(int id) {
        discussPostService.updateStatus(id, PostConstant.ESSENCE);
        // 发布发帖消息
        Event event = new Event();
        event.setTopic(TopicConstant.PUBLISH);
        event.put("postId",id);
        eventProducer.fireEvent(event);
        // 将帖子ID放入Redis的待刷新集合中 无序不重复集合
        redisTemplate.opsForSet().add(RedisUtil.getNeedRefreshScorePostsKey(),id);
        return R.success();
    }

    @DeleteMapping("/remove")
    @ResponseBody
    public R remove(int id) {
        discussPostService.updateStatus(id, PostConstant.DELETED);
        // 发布删帖消息
        Event event = new Event();
        event.setTopic(TopicConstant.POST_DELETE);
        event.put("postId",id);
        eventProducer.fireEvent(event);
        return R.success();
    }

}



